<template>
  <div>
    <div class="title">
        <span>默认分账关系配置</span>
        <span :key="key"></span>
        <div>
            <el-button type="primary" @click="openMerSplit">新增默认关系配置</el-button>
            <el-button
            icon="el-icon-refresh"
            @click.native="updateClick()"
            ></el-button>
        </div>
    </div>
    <div class="container">
      <!-- 搜索板块 -->
      <div class="screeningBox">
        <el-form ref="searchObj" :model="searchObj">
          <div class="leftBox" v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8">
              <div class="leftitem">
                  <el-form-item class="ipt" prop="merchantNo">
                      <el-input placeholder="商户号"  v-model="searchObj.merchantNo"></el-input>
                  </el-form-item>
              </div>
              <div class="leftitem">
                  <el-form-item class="ipt" prop="merchantName">
                      <el-input placeholder="商户名" v-model="searchObj.merchantName"></el-input>
                  </el-form-item>
              </div>
          </div>
          <div class="leftBox">
        
              <div class="leftitem">
                <el-form-item style="text-align:right">
                  <el-button icon="el-icon-search" type="primary" @click="soso" :disabled="isDisable">
                    搜索
                  </el-button>
                  <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
                </el-form-item>
              </div>
          </div>
        </el-form>
      </div>

      <!-- 表格板块 -->
      <div class="tableBox">
          <el-table
                ref="multipleTable"
                :data="merSplitData"
                tooltip-effect="dark"
                style="width: 100%"
                stripe
                v-loading="loading"
                :header-cell-style="tableHeaderColor">
            <el-table-column
                prop="id"
                align="center"
                label="序号"
                width="60"
            ></el-table-column>
            <el-table-column
                prop="merchantNo"
                label="商户号"
                align="center"
            ></el-table-column>
            <el-table-column
                prop="merchantName"
                label="商户名"
                align="center"
            ></el-table-column>
            <el-table-column
                prop="channelName"
                label="通道名称"
                align="center"
            ></el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间"
                align="center"
            ></el-table-column>
            <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="120"
            >
                <template slot-scope="scope">
                  <el-button
                      type="text"
                      size="small"
                      @click="merSplitDetail(scope.row)">
                      详情
                  </el-button>
                  <el-button
                      type="text"
                      size="small"
                      @click="deletMerSplitFn(scope.row)">
                      删除
                  </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-sizes="[10,20,30,40,50]"
            :page-size='cur_size'
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :current-page.sync="cur_page"
        ></el-pagination>
        </div>
      </div>

      <!-- 分账配置 -->
      <el-dialog
          title="默认分账配置"
          center
          :visible.sync="merSplitVisible"
          @closed="merSplitClose"
          @opened="onmerSplitOpen"
          width="1000px"
          :close-on-click-modal="false">
          <el-form ref="merSplitForm" class="split-form" label-position="left" label-width="100px" :model="merSplitForm" :rules="merSplitFormRules">
            <div class="merSplit">
              <el-form-item class="ipt" prop="merchantName" label="分账商户名" v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8">
              <el-autocomplete
              style="width: 90%"
              v-model.trim="merSplitForm.merchantName"
              :fetch-suggestions="merchantslist"
              :trigger-on-focus="false"
              :debounce="300"
              placeholder="分账商户名"
              @select="okmerchants">
            </el-autocomplete>
            </el-form-item>
            <el-form-item class="ipt" prop="channelId" label="通道类型">
              <el-select style="width: 90%;" v-model="merSplitForm.channelId"  placeholder="通道类型" @change="channelChange">
                <el-option v-for= '(item) in channelinfo' :key='item.channelId' :label='item.channelName' :value="item.channelId"></el-option>
              </el-select>
            </el-form-item>
            </div>
            <div class="feeMerchant">
              <div class="split-box">
              <div>
                <el-form-item prop="percent" label-width="0">
                  <el-input placeholder="请输入分账比例" style="width: 100%;" v-model.trim="merSplitForm.percent"></el-input>
                </el-form-item>
                <div style="margin: 5px 0 0px 0px; font-size: 13px;">
                  <i class="el-icon-question" style="margin-right: 5px"></i>
                  <span class="ratio-tips">分账比例取值范围（%）：0.01~100，可精确到2位小数</span>
                </div>
              </div>
              <div style="margin-left: 10px;">
                <el-form-item label-width="0">
                  <el-autocomplete
                    style="width: 60%;"
                    v-model.trim="bySplitMer.merchantName"
                    :fetch-suggestions="bymerchantslist"
                    :trigger-on-focus="false"
                    :debounce="300"
                    placeholder="被分账商户"
                    @select="okBymerchants">
                  </el-autocomplete>
                  <el-button type="primary" style="margin-left: 10px" @click="addBySplitMer"><i class="el-icon-lx-add"></i>添加</el-button>
                </el-form-item>
              </div>
              </div>
                <el-table
                  ref="singleTable"
                  :data="merSplitInfo.splitMerchantInfos"
                  @select="select"
                  :header-cell-style="tableHeaderColor"
                  style="width: 100%; margin-top: 20px;">
                  <el-table-column type="selection" width="55"></el-table-column>
                  <el-table-column
                    prop="merchantName"
                    label="商户名">
                  </el-table-column>
                  <el-table-column
                    prop="merchantNo"
                    label="商户号">
                  </el-table-column>
                  <el-table-column
                    prop="percent"
                    label="分账比例(%)">
                  </el-table-column>
                </el-table>
                <div style="margin: 5px 0 5px 0px; font-size: 13px;">
                  <i class="el-icon-question" style="margin-right: 5px"></i>
                  <span class="ratio-tips">勾选被分账商户为手续费承担方，不勾选默认分账方为手续费承担方</span>
                </div>
                <el-form-item style="text-align:right; margin-top: 20px;">
                  <el-button type="primary" @click="onSubmit">确定</el-button>
                  <el-button @click="merSplitClose">取消</el-button>
              </el-form-item>
            </div>
          </el-form>
        </el-dialog>
    </div>
  </div>
</template>

<script>
import { getMerDefaultSplit, saveMerSplit, deletMerSplit } from '@/api/defaultsplit/defaultsplit.js'
import { getMerSplitChannelInfo } from '@/api/splitrelation/splitrelation.js'
import { merchantlist, channel } from '@/api/api'
import { getTimeFn } from '@/utils/getday.js'
export default {
  name: 'DefaultSplit',

  data() {
    var checkPercent = (rule, value, cb) => {
      if(this.merSplitInfo.splitMerchantInfos.length > 0) {
        return cb()
      }
        // 分账比例的正则表达式
      const regRatio = /^(0\.(0[1-9]|[1-9]\d{0,1})|[1-9]\d{0,1}(\.\d{1,2})?|100(\.0{1,2})?)$/
      if (regRatio.test(value)) {
          //合法的分摊比例
          return cb()
      }
      cb(new Error('请填写正确的分摊比例'))
    }
    return {
      pickerOptions: {
        disabledDate(time) {
        let nowDate = new Date();
        let date = {
            year: nowDate.getFullYear(),
            month: nowDate.getMonth() + 1,
            date: nowDate.getDate(),
        };
        let timeDate =
            date.year + "-" + date.month + "-" + date.date + " 23:59:59";
        let times = new Date(timeDate).getTime();
        return time.getTime() > times;
        },
      },
      merSplitFormRules: {
        merchantName: [
          { required: true, message: '请选择分账商户', trigger: 'blur' }
        ],
        channelId: [
          { required: true, message: '请选择通道类型', trigger: 'change' }
        ],
        percent: [
          { validator: checkPercent, trigger: 'blur' }
        ],
        // feeMerchantId: [
        //   { validator: checkFeeMerchantiId, trigger: '' }
        // ]
      },
      key: 0,
      getTitle: '默认分账配置',
      cur_page: 1,
      cur_size: 10,
      total: 0,
      loading: false,
      isDisable: false,
      merSplitVisible: false,
      date: '',
      searchObj: {
        merchantId: '',
        merchantNo: '',
        merchantName: '',
        startTime: '',
        endTime: '',
      },
      merSplitData: [],
      channelinfo: [],
      merchantarrlist: [],
      merSplitInfo: {
        splitMerchantInfos: []
      },
      merSplitForm: {
        percent: '',
      },
      bySplitMer: {},
      userinfo: {}
    };
  },

  created() {
    this.userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
    this.getMerDefaultSplitFn()
  },

  methods: {
    //修改thead 背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
            return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
        }
    },
    // 分页导航
    handleCurrentChange(val) {
        this.cur_page = val;
        this.getMerDefaultSplitFn()
        this.$nextTick(() => {
            document.querySelectorAll(".content")[0].scrollTop = "0";
        });
    },
    // 分页数量
    sizechange(val) {
        this.cur_size = val;
        this.getMerDefaultSplitFn()
        this.$nextTick(() => {
            document.querySelectorAll(".content")[0].scrollTop = "0";
        });
    },
    // 刷新
    updateClick() {
      this.loading = true;
      this.getMerDefaultSplitFn();
      this.handleCurrentChange(1)
    },
    // 搜索
    soso() {
      this.isDisable = true
      this.handleCurrentChange(1)
    },
    // 重置
    reset() {
        this.$refs.searchObj.resetFields()
    },
    // 获取商户默认分账列表
    async getMerDefaultSplitFn() {
      let list = {
        merchantId: this.searchObj.merchantId,
        merchantNo: this.searchObj.merchantNo,
        merchantName: this.searchObj.merchantName,
        startTime: '',
        finishTime: '',
        page: this.cur_page,
        size: this.cur_size,
      }
      let res = await getMerDefaultSplit(list)
      if(res.code == 405) {
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.merSplitData = res.data.rows
        this.cur_page = res.data.currPage
        this.cur_size = res.data.pageSize
        this.total = res.data.total
      }
      this.isDisable = false
      this.loading = false
    },
    // 打开配置弹窗
    openMerSplit() {
      this.merSplitVisible = true
    },
    onmerSplitOpen() {
      if(this.userinfo.rolesId == 5) {
        this.merSplitForm.merchantId = this.userinfo.fid
        this.getChannelFn(this.userinfo.fid)
      }
    },
    // 关闭配置弹窗
    merSplitClose() {
      this.$refs.merSplitForm.resetFields()
      this.$refs.singleTable.setCurrentRow('')
      this.merSplitForm.feeMerchantId = ''
      this.merchantarrlist = []
      this.channelinfo = []
      this.bySplitMer = {}
      this.merSplitInfo.splitMerchantInfos = []
      this.merSplitVisible = false
    },
    // 获取通道列表
    async getChannelFn(id) {
      let res = await getMerSplitChannelInfo(id)
      if(res.code == 405) {
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.channelinfo = res.data
      }
    },
    // 获取商户列表初始化
    merchantslist(queryString, cb) {
    let sosolist = {};
    sosolist = {
        page: 1,
        size: 20,
        merchantName: this.merSplitForm.merchantName,
    };
    merchantlist(sosolist).then((res) => {
        // console.log(res);
        if (res.code == 405) {
            sessionStorage.removeItem("token");
            this.$router.push("/login");
        } else {
        this.merchantarrlist = [];
        for (var i = 0; i < res.data.length; i++) {
            this.merchantarrlist.push({
            value: res.data[i].merchantName,
            merchantId: res.data[i].id,
            merchantNo: res.data[i].merchantNo
            });
        }
        let results = queryString
            ? this.merchantarrlist.filter(this.createFilter(queryString))
            : this.merchantarrlist;
        // 调用 callback 返回建议列表的数据
        cb(results);
        }
    });
    },
    // 被分账商户初始化
    bymerchantslist(queryString, cb) {
    let sosolist = {};
    sosolist = {
        page: 1,
        size: 20,
        merchantName: this.bySplitMer.merchantName,
    };
    merchantlist(sosolist).then((res) => {
        // console.log(res);
        if (res.code == 405) {
            sessionStorage.removeItem("token");
            this.$router.push("/login");
        } else {
        this.merchantarrlist = [];
        for (var i = 0; i < res.data.length; i++) {
            this.merchantarrlist.push({
            value: res.data[i].merchantName,
            merchantId: res.data[i].id,
            merchantNo: res.data[i].merchantNo
            });
        }
        let results = queryString
            ? this.merchantarrlist.filter(this.createFilter(queryString))
            : this.merchantarrlist;
        // 调用 callback 返回建议列表的数据
        cb(results);
        }
    });
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    select(selection, row) {
      // 清除 所有勾选项
      this.$refs.singleTable.clearSelection()
      // 当表格数据都没有被勾选的时候 就返回
      // 主要用于将当前勾选的表格状态清除
      if(selection.length == 0) {
        this.merSplitForm.feeMerchantId = ''
        return
      }
      this.$refs.singleTable.toggleRowSelection(row, true);
      this.merSplitForm.feeMerchantId = row.merchantId
    },
    // 选择商户
    okmerchants(val) {
        this.merSplitForm.merchantId = val.merchantId;
        this.merSplitForm.merchantNo = val.merchantNo
        this.getChannelFn(val.merchantId)
    },
    // 选择被分账商户
    okBymerchants(val) {
        this.bySplitMer.merchantId = val.merchantId;
        this.bySplitMer.merchantNo = val.merchantNo;
    },
    // 通道选中
    channelChange(val) {
      this.channelinfo.forEach((item,index) => {
        if(item.channelId == val) {
          this.merSplitForm.channelName = item.channelName
          this.merSplitForm.channelType = item.channelType
        }
      })
    },
    // 添加被分账商户
    addBySplitMer() {
      this.$refs.merSplitForm.validate(async(valid) => {
        if(valid) {
          if(this.bySplitMer.merchantId == this.merSplitForm.merchantId) {
            this.$message.error('被分账商户不能和分账商户相同')
            return
          } else if (this.merSplitInfo.splitMerchantInfos.some((item) => { return this.bySplitMer.merchantId == item.merchantId })) {
            this.$message.error('已存在相同的被分账商户')
            return
          } else if (this.bySplitMer.merchantName == undefined || this.bySplitMer.merchantName == ''){
            this.$message.error('请选择被分账商户')
            return
          } else if (this.merSplitForm.percent == '' || this.merSplitForm.percent == undefined) {
            this.$message.error('分账比例不能为空')
            return
          }else {
            if(this.merSplitInfo.splitMerchantInfos.length > 0) {
              let total = 0
              this.merSplitInfo.splitMerchantInfos.forEach(item => {
                total += item.percent
              })
              if(total + this.merSplitForm.percent > 100) {
                this.$message.error('分账比例合计不能超过100')
                return
              }
            }
            this.bySplitMer.percent = this.merSplitForm.percent
            this.merSplitInfo.splitMerchantInfos.unshift({
              merchantId: this.bySplitMer.merchantId,
              merchantNo: this.bySplitMer.merchantNo,
              merchantName: this.bySplitMer.merchantName,
              percent: this.bySplitMer.percent,
            })
            this.merSplitForm.percent = undefined
            this.bySplitMer = {}
          }
        }
      })
    },
    // 提交
    onSubmit() {
      this.$refs.merSplitForm.validate(async(valid) => {
        if(valid) {
          if(this.merSplitForm.merchantId == this.merSplitForm.feeMerchantId) {
            this.$message.error('分账商户和被分账商户不能为同一个商户')
            return
          } else {
            let splitInfo = []
            this.merSplitInfo.splitMerchantInfos.forEach((item) => {
              splitInfo.push({
                merchantId: item.merchantId,
                percent: item.percent
                })
              })
              let feeMerchantId = this.merSplitForm.feeMerchantId ? this.merSplitForm.feeMerchantId : this.merSplitForm.merchantId
              let list = {
                merchantId: this.merSplitForm.merchantId,
                merchantNo: this.merSplitForm.merchantNo,
                merchantName: this.merSplitForm.merchantName,
                channelId: this.merSplitForm.channelId,
                channelType: this.merSplitForm.channelType,
                channelName: this.merSplitForm.channelName,
                splitInfo: JSON.stringify(splitInfo),
                feeMerchantId: feeMerchantId
              }
              let res = await saveMerSplit(list)
              if(res.code == 405) {
                sessionStorage.removeItem("token");
                this.$router.push("/login");
              } else {
                if(res.code == 200) {
                  this.$message.success('新增默认分账关系成功')
                  this.merSplitClose()
                  this.getMerDefaultSplitFn()
                } else {
                  this.$message.error(res.message)
                }
              }
            }
        }
      })
    },
    // 默认分账详情
    merSplitDetail(val) {
      this.$router.push({
        path: '/defaultsplitdetail',
      })
      sessionStorage.setItem('merSplitId', JSON.stringify(val.id))
    },
    // 删除默认分账配置
    deletMerSplitFn(val) {
      this.$confirm("是否确定删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async() => {
          let res = await deletMerSplit(val.id)
            if(res.code == 405) {
              sessionStorage.removeItem("token");
              this.$router.push("/login");
            } else {
              this.$message.success(res.message)
              if(this.merSplitData.length == 1) {
                this.cur_page = this.cur_page - 1
              }
            }
        })
        .catch(() => {});
        this.getMerDefaultSplitFn()
    }
  },
};
</script>

<style lang="less" scoped>
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 30%;
  padding: 0 15px;
  box-sizing: border-box;
}
.rightBox {
    width: 70%;
}
.leftBox > .leftitem,
.rightBox > .leftitem {
  display: flex;
}

.screeningBox .el-form{
    display: flex;
    width: 100%;
}
.ipt {
    width: 70%;
    margin-right: 10px;
    margin-bottom: 15px;
}
.tableBox {
  margin-top: 20px;
}
.feeMerchant{
  margin-top: 10px;
  border-top: 1px dashed #c0c4cc;
  padding: 20px 10px 0 10px;

}

.split-box{ 
  display: flex;
}
.split-box > div {
  width: 350px;
}
.split-box > div:nth-child(2) {
  width: 500px;
}

/deep/.el-table__header-wrapper  .el-checkbox{
	display:none
}
</style>